package net.sppan.blog.controller.admin;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import net.sppan.blog.annotation.RequiresPermissions;
import net.sppan.blog.controller.BaseController;
import net.sppan.blog.model.Config;
import net.sppan.blog.model.Role;
import net.sppan.blog.utils.AESUtil;
import net.sppan.blog.utils.Const;

import com.jfinal.aop.Clear;
import com.jfinal.kit.PathKit;
import com.jfinal.upload.UploadFile;

@RequiresPermissions(key = { "admin:sys:user" })
public class AdminConfigController extends BaseController {

	@RequiresPermissions(key = { "admin:sys:config:save" })
	public void index() {
		Role role = getSessionAttr("loginUserRole");
		if (!Const.Administrator.equals(role.getName())) {
			renderJson("no permission");
			return;
		}
		Config config = Config.dao.findFirst("select * from sys_config");
		setAttr("config", config);
		render("form.html");

	}

	@RequiresPermissions(key = { "admin:sys:config:save" })
	public void upload() {
		boolean flag = true;
		UploadFile uploadFile = this.getFile("file");
		if (uploadFile == null) {
			flag = false;
		}
		Config c = getModel(Config.class);

		if (flag) {
			File file = uploadFile.getFile();
			String fullFolderPath = PathKit.getWebRootPath() + File.separator + "uploadpkg";
			File outFolder = new File(fullFolderPath);
			if (!outFolder.exists()) {
				outFolder.mkdirs();
			} else {
				delAllFile(fullFolderPath);
			}
			String fileName = file.getName(); //获取文件名（含后缀）
			c.setUpdateUrl(fileName);
			String fullFilePath = fullFolderPath + File.separator + fileName; // 文件全路径
			BufferedInputStream in = null;
			BufferedOutputStream out = null;
			try {
				File outFile = new File(fullFilePath);
				if (!outFile.exists()) {
					outFile.createNewFile();
				}
				out = new BufferedOutputStream(new FileOutputStream(outFile)); // 创建文件输出流
				in = new BufferedInputStream(new FileInputStream(file));
				byte[] buffer = new byte[1024];
				int byteread = 0;
				while ((byteread = in.read(buffer)) != -1) {
					out.write(buffer, 0, byteread);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (in != null) {
						in.close();
					}
					if (out != null) {
						out.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		renderJson(c.update(), "success");
	}

	public boolean delAllFile(String path) {
		boolean flag = false;
		File file = new File(path);
		if (!file.exists()) {
			return flag;
		}
		if (!file.isDirectory()) {
			return flag;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
		}
		return flag;
	}

	@Clear
	public void download() {
		String p = getPara("p");
		if (p == null) {
			return;
		}
		if (checkTime(p)) {
			return;
		}
		String filePath = "";
		try {
			String fullFolderPath = PathKit.getWebRootPath() + File.separator + "uploadpkg";
			File file = new File(fullFolderPath);
			String[] tempList = file.list();
			File temp = null;
			for (int i = 0; i < tempList.length; i++) {
				if (fullFolderPath.endsWith(File.separator)) {
					temp = new File(fullFolderPath + tempList[i]);
				} else {
					temp = new File(fullFolderPath + File.separator + tempList[i]);
				}
				if (temp.isFile()) {
					filePath = temp.getAbsolutePath();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		File file = new File(filePath);
		if (file.exists()) { //如果文件存在
			renderFile(file);
		} else {
			renderJson();
		}

	}

	private boolean checkTime(String p) {
		boolean error = false;
		try {
			String time = AESUtil.desEncrypt(p).trim();
			if ((System.currentTimeMillis() - Long.parseLong(time)) > 1000 * 60 * 10) {
				error = true;
			}
		} catch (Exception e) {
			error = true;
			e.printStackTrace();
		}
		return error;
	}

	public static void main(String[] args) {
		System.out.println(AESUtil.encrypt(System.currentTimeMillis() + ""));
	}
}
